In Elixir, processes are short-lived by default; once a function finishes, the process terminates. To create a persistent, stateful process, we use recursion to keep the process alive in a loop.
1. Tail-Call Optimization (TCO)
If the absolute final action of a function is to call itself, the Erlang VM (BEAM) performs Tail-Call Optimization. Instead of adding a new frame to the stack, it simply jumps back to the start of the function with new arguments.
def factorial(n, acc), do: _fact(n-1, acc*n) # TCO
def factorial(n), do: n * factorial(n-1) # NOT TCO
def factorial(n), do: n * factorial(n-1) # NOT TCO
2. Persistent State
State is maintained by passing updated values as arguments to the recursive call. Because of TCO, these arguments replace original parameters on the stack without consuming additional memory, allowing loops to run indefinitely.
TERMINAL
bash — 80x24
> Ready. Click "Run" to execute.
>